package com.example.feild.encryption.domain.service;

import com.alibaba.fastjson.JSON;
import com.example.feild.encryption.domain.dao.mappers.DemoStaffMapper;
import com.example.feild.encryption.domain.pojo.model.DemoStaff;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (DemoStaff)表服务实现类
 * @author makejava
 * @since 2020-04-27 10:51:05
 */
@Service
public class DemoStaffService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoStaffService.class);

    @Autowired(required = false)
    private DemoStaffMapper demoStaffMapper;

    /**
     * 新增数据
     * @return 实例对象
     */
    @Transactional
    public void batchInsert() {
        List<DemoStaff> list = new ArrayList<>();
        Date now = new Date();
        for (int i = 0; i < 5; i++) {
            DemoStaff entity = new DemoStaff();
            //姓名
            entity.setName(RandomStringUtils.random(8));
            //年龄
            entity.setAge(RandomUtils.nextInt(10, 50));
            //创建时间
            entity.setCreate_time(now);
            //修改时间
            entity.setUpdate_time(now);
            list.add(entity);
        }
        demoStaffMapper.insertList(list);
    }

    @Transactional
    public DemoStaff batchUpdate() {
        List<DemoStaff> list = demoStaffMapper.selectAll();
        list.stream().forEach(x -> x.setName("张力"));
        demoStaffMapper.batchUpdateByPrimaryKeySelective(list);
        return null;
    }

    @Transactional
    public void batchDelete() {
        List<String> list = demoStaffMapper.selectAll().stream().map(x -> "'" + x.getStaff_id() + "'").collect(Collectors.toList());
        this.demoStaffMapper.deleteByIds(StringUtils.join(list.toArray(), ","));
        LOGGER.info(JSON.toJSONString(demoStaffMapper.selectByPrimaryKey(1)));
    }
}